<template>
  <div class="traffic-info-container">
    <div class="map-container" ref="mapContainer">
    </div>

    <!-- Control Panel -->
    <div class="control-panel" id="tools-container">
      <h3 class="panel-title">交通信息</h3>
      <p class="panel-description">查看道路交通态势</p>

      <el-button
        type="warning"
        @click="checkRoadTraffic"
        class="traffic-button"
        :disabled="showTraffic"
      >
        查看103省道交通态势
      </el-button>
    </div>

    <!-- Traffic Info Panel -->
    <el-card
      v-if="showTraffic"
      class="traffic-info-panel"
      :body-style="{ padding: '15px' }"
    >
      <template #header>
        <div class="traffic-header">
          <span>103省道交通态势</span>
          <el-button
            type="danger"
            size="small"
            @click="showTraffic = false"
            class="close-button"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>

      <div v-if="trafficInfo && trafficInfo.trafficinfo && trafficInfo.trafficinfo.evaluation" class="traffic-content">
        <div class="traffic-status">
          <div class="status-label">道路状态:</div>
          <div
            class="status-value"
            :class="{
              'status-smooth': trafficInfo.trafficinfo.evaluation.status === '0',
              'status-slow': trafficInfo.trafficinfo.evaluation.status === '1',
              'status-congested': trafficInfo.trafficinfo.evaluation.status === '2',
              'status-blocked': trafficInfo.trafficinfo.evaluation.status === '3',
            }"
          >
            {{
              trafficInfo.trafficinfo.evaluation.status === '0'
                ? '畅通'
                : trafficInfo.trafficinfo.evaluation.status === '1'
                ? '缓行'
                : trafficInfo.trafficinfo.evaluation.status === '2'
                ? '拥堵'
                : trafficInfo.trafficinfo.evaluation.status === '3'
                ? '严重拥堵'
                : '未知'
            }}
          </div>
        </div>

        <div class="traffic-detail">
          <div class="detail-item">
            <div class="detail-label">畅通路段比例:</div>
            <div class="detail-value">{{ trafficInfo.trafficinfo.evaluation.expedite }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">缓行路段比例:</div>
            <div class="detail-value">{{ trafficInfo.trafficinfo.evaluation.congested }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">拥堵路段比例:</div>
            <div class="detail-value">{{ trafficInfo.trafficinfo.evaluation.blocked }}</div>
          </div>
        </div>

        <div class="traffic-description">
          <div class="description-label">详细描述:</div>
          <div class="description-value">
            {{ trafficInfo.trafficinfo.description || trafficInfo.trafficinfo.evaluation.description || '暂无详细描述' }}
          </div>
        </div>
      </div>
      <div v-else class="traffic-loading">
        <el-icon class="is-loading"><Loading /></el-icon> 正在获取交通信息...
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Close, Loading } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { getGaoDeTraffic, type GaoDeTrafficResponse } from '@/utils/gaodeAPI'
import {
  facilityPointSymbol,
  scenicPointSymbol,
  viewScenicSpotSymbol,
  serviceSymbol,
  monitorSymbol,
  trafficSymbol,
  greenSymbol
} from '@/utils/facilityIcons'

const mapContainer = ref<HTMLDivElement>()

// Create point symbols for different facility types
// 使用统一的设施图标符号（已从 facilityIcons.ts 导入）

// Create road symbol
const roadSymbol = new SimpleLineSymbol({
  color: [0, 122, 194, 0.8],
  width: 4,
  style: 'solid',
  cap: 'round',
  join: 'round',
})

// Create facility layer
const facilityLayer = new FeatureLayer({
  url: 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'unique-value',
    field: 'facilitytype',
    defaultSymbol: facilityPointSymbol,
    uniqueValueInfos: [
      {
        value: '驿站',
        symbol: scenicPointSymbol,
      },
      {
        value: '景点',
        symbol: viewScenicSpotSymbol,
      },
      {
        value: '餐饮',
        symbol: facilityPointSymbol,
      },
    ],
  } as never,
})

// Create road layer
const roadLayer = new FeatureLayer({
  url: 'https://www.geosceneonline.cn/server/rest/services/Hosted/S103/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'simple',
    symbol: roadSymbol,
  } as never,
})

// Create sketch layer for drawing
const sketchLayer = new GraphicsLayer({
  title: '绘图图层',
})

// Create map
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})

// Add layers to map
map.add(facilityLayer)
map.add(roadLayer)
map.add(sketchLayer)

// Create map view
const view = new MapView({
  map: map,
  center: [117.14435714426122, 36.29746937366678],
  zoom: 10,
})

// Initialize map view in onMounted
onMounted(() => {
  // Initialize map view container
  view.container = mapContainer.value as HTMLDivElement
  view.ui.add('tools-container', 'top-right')
})

// Traffic related state
const trafficInfo = ref<GaoDeTrafficResponse | null>(null)
const showTraffic = ref(false)

// Check road traffic
async function checkRoadTraffic() {
  try {
    showTraffic.value = true
    trafficInfo.value = null // Reset traffic info

    // Get traffic information from GaoDe API
    const response = await getGaoDeTraffic('103省道', '370100')
    console.log('交通信息API响应:', response)

    // 检查响应结构
    if (!response) {
      ElMessage.error('获取交通信息失败: 响应为空')
      showTraffic.value = false
      return
    }

    if (response.status !== '1') {
      ElMessage.error('获取交通信息失败: ' + response.info)
      showTraffic.value = false
      return
    }

    // 检查响应中是否包含必要的字段
    if (!response.trafficinfo) {
      ElMessage.error('获取交通信息失败: 响应中缺少交通信息数据')
      console.error('响应中缺少trafficinfo字段:', response)
      showTraffic.value = false
      return
    }

    if (!response.trafficinfo.evaluation) {
      ElMessage.error('获取交通信息失败: 响应中缺少评估数据')
      console.error('响应中缺少evaluation字段:', response.trafficinfo)
      showTraffic.value = false
      return
    }

    // 设置交通信息
    trafficInfo.value = response

    // Center the map on the road
    view.goTo({
      center: [117.14435714426122, 36.29746937366678],
      zoom: 10
    })

    ElMessage.success('已获取103省道交通态势')
  } catch (error) {
    console.error('获取交通信息失败:', error)
    ElMessage.error('获取交通信息失败')
    showTraffic.value = false
  }
}
</script>

<style scoped>
.traffic-info-container {
  height: 100%;
  width: 100%;
  position: relative;
}

.map-container {
  height: 100%;
  width: 100%;
  position: relative;
}

/* Control panel styles */
.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(24, 44, 78, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.15);
  transition: all 0.3s ease;
  color: #fff;
  width: 280px;
}

.panel-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #fff;
}

.panel-description {
  margin-bottom: 15px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.traffic-button {
  width: 100%;
}

/* Traffic info panel styles */
.traffic-info-panel {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 320px;
  z-index: 2000;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.traffic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

:deep(.el-card__header) {
  background: linear-gradient(135deg, #1976D2, #42A5F5);
  color: white;
  padding: 12px 15px;
  border-bottom: none;
}

.close-button {
  padding: 5px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.traffic-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.traffic-status {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
}

.status-label {
  font-weight: 600;
  color: #333;
}

.status-value {
  font-weight: 600;
  padding: 4px 12px;
  border-radius: 4px;
  color: white;
}

.status-smooth {
  background-color: #67c23a;
}

.status-slow {
  background-color: #e6a23c;
}

.status-congested {
  background-color: #f56c6c;
}

.status-blocked {
  background-color: #f56c6c;
}

.traffic-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-label {
  color: #606266;
}

.detail-value {
  font-weight: 600;
  color: #333;
}

.traffic-description {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
}

.description-label {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.description-value {
  color: #606266;
  line-height: 1.5;
}

.traffic-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  height: 100px;
  color: #909399;
}
</style>
